<style scoped>
.medical-form {
  .form-row {
    display: flex;
  }
}

.medical-form .form-row {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.medical-form .form-row label {
  flex: 0 0 120px;
  text-align: right;
  padding-right: 15px;
  line-height: 40px;
  color: #606266;
}

.medical-form .form-row input,
.medical-form .form-row textarea,
.medical-form .form-row select {
  flex: 1;
  padding: 8px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.medical-form .form-row input:focus,
.medical-form .form-row textarea:focus,
.medical-form .form-row select:focus {
  outline: none;
  border-color: #409eff;
}

/* 其他嵌套样式同理修改为普通CSS选择器 */

.prescription-form {
  padding: 20px;
  height: calc(100vh - 200px);
  overflow-y: auto;
}

/* 添加处方按钮组样式 */
.prescription-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 10px;
}

.prescription-button {
  min-width: 100px;
  height: 36px !important;
  font-size: 14px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.prescription-button i {
  margin-right: 4px;
  font-size: 16px;
}

.prescription-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.prescription-button.primary {
  background: #2d8cf0;
  color: white;
  border-color: #2d8cf0;
  margin-left: 10px;
}

.prescription-button.success {
  background: #19be6b;
  color: white;
  border-color: #19be6b;
}

.prescription-button.warning {
  background: #ff9900;
  color: white;
  border-color: #ff9900;
}

.prescription-button.error {
  background: #ed4014;
  color: white;
  border-color: #ed4014;
}

.medicine-item {
  margin-bottom: 16px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  position: relative;
}

.medicine-suggestions {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.suggestion-item {
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.suggestion-item:hover {
  background-color: #f5f7fa;
}

.medicine-item .ivu-row {
  margin-bottom: 0;
}

.medicine-item .ivu-input {
  width: 100%;
}

@media (max-width: 1200px) {
  .medicine-item .ivu-col {
    margin-bottom: 8px;
  }
}

.medical-record {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
  position: relative;
}

.record-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
  position: relative;
}

.medical-tabs {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 60px; /* 为底部按钮留出空间 */
}

.action-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: white;
  border-top: 1px solid #ebeef5;
  text-align: center;
  z-index: 10;
}

.action-bar .ivu-btn {
  height: 32px;
  line-height: 32px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-actions .ivu-btn {
  height: 32px;
  line-height: 32px;
}

/* 确保日期选择器显示在最上层 */
.ivu-date-picker-cells {
  z-index: 1000;
}

.ivu-select-dropdown {
  z-index: 1000;
}

.assistant-card {
  height: calc(100vh - 40px);
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.assistant-header {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  flex-shrink: 0;
}

.assistant-tools {
  margin-left: auto;
  display: flex;
  gap: 12px;
}

.assistant-tools i {
  font-size: 18px;
  cursor: pointer;
  color: #606266;
  transition: color 0.3s;
}

.assistant-tools i:hover {
  color: #409eff;
}

.quick-actions {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  background: white;
  flex-shrink: 0;
  display: flex;
  gap: 8px;
}

.quick-action-btn {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f8f9fa;
  color: #515a6e;
  border: 1px solid #dcdfe6;
}

.quick-action-btn i {
  margin-right: 4px;
  font-size: 16px;
}

.quick-action-btn:hover {
  background: #ecf5ff;
  color: #409eff;
  border-color: #b3d8ff;
}

.quick-action-btn:active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.patient-summary {
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.summary-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.summary-content {
  font-size: 13px;
  color: #606266;
}

.summary-content p {
  margin: 4px 0;
}

.chat-container {
  height: 400px; /* 固定高度 */
  overflow-y: auto;
  padding: 16px;
  background: #f8f9fa;
}

.message {
  margin-bottom: 10px;
  max-width: 90%;
}

.message-header {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-type {
  font-weight: 500;
}

.message-time {
  color: #c0c4cc;
}

.user-message {
  margin-left: auto;
}

.ai-message {
  margin-right: auto;
}

.message-content {
  padding: 12px 16px;
  border-radius: 12px;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
}

/* 添加等待动画样式 */
.typing-indicator {
  display: flex;
  align-items: center;
  padding: 8px 12px;
}

.typing-dot {
  width: 8px;
  height: 8px;
  margin: 0 2px;
  background-color: #409eff;
  border-radius: 50%;
  animation: typing 1s infinite ease-in-out;
}

.typing-dot:nth-child(1) { animation-delay: 0s; }
.typing-dot:nth-child(2) { animation-delay: 0.2s; }
.typing-dot:nth-child(3) { animation-delay: 0.4s; }

@keyframes typing {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

/* 优化AI回复样式 */
.ai-message .message-content {
  background: white;
  color: #303133;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.ai-message .message-content pre {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  margin: 8px 0;
  overflow-x: auto;
}

.ai-message .message-content code {
  font-family: monospace;
  background: #f1f1f1;
  padding: 2px 4px;
  border-radius: 3px;
}

.ai-message .message-content ul, 
.ai-message .message-content ol {
  padding-left: 20px;
  margin: 8px 0;
}

.ai-message .message-content p {
  margin: 8px 0;
}

.ai-message .message-content blockquote {
  border-left: 4px solid #dcdfe6;
  margin: 8px 0;
  padding-left: 12px;
  color: #606266;
}

.user-message .message-content {
  background: #409eff;
  color: white;
}

.streaming-char {
  display: inline-block;
  animation: fadeIn 0.1s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(2px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.input-section {
  padding: 16px;
  border-top: 1px solid #ebeef5;
  background: white;
  flex-shrink: 0;
}

.input-wrapper {
  margin-bottom: 8px;
}

/* 自定义滚动条样式 */
.chat-container::-webkit-scrollbar {
  width: 4px;
}

.chat-container::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 2px;
}

.chat-container::-webkit-scrollbar-track {
  background-color: transparent;
}

.chat-container::-webkit-scrollbar-thumb:hover {
  background-color: #c0c4cc;
}

@media (max-width: 1200px) {
  .assistant-card {
    height: 600px;
    margin-top: 20px;
  }
  
  .chat-container {
    height: 400px; /* 保持与PC端一致的高度 */
  }
}

.revision-history {
  max-height: 500px;
  overflow-y: auto;
  padding: 20px;
}

.revision-time {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.revision-reason {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.revision-user {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.revision-content {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
}

.content-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.content-diff {
  display: flex;
  gap: 20px;
}

.original-content,
.revised-content {
  flex: 1;
}

.diff-title {
  font-size: 13px;
  color: #606266;
  margin-bottom: 4px;
}

.diff-text {
  font-size: 13px;
  color: #303133;
  white-space: pre-wrap;
  background: white;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
}

.medicine-tag {
  cursor: pointer;
  margin: 4px;
  padding: 4px 8px;
}

.medicine-tag:hover {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.medicine-list-container {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.medicine-list-container::-webkit-scrollbar {
  width: 6px;
}

.medicine-list-container::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.medicine-list-container::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.frequent-medicines {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
  padding: 8px;
  max-height: 200px;
  overflow-y: auto;
  background: #f8f9fa;
  border-radius: 4px;
}

.frequent-medicines::-webkit-scrollbar {
  width: 6px;
}

.frequent-medicines::-webkit-scrollbar-thumb {
  background-color: #c0c4cc;
  border-radius: 3px;
}

.frequent-medicines::-webkit-scrollbar-track {
  background-color: transparent;
}

.medicine-card {
  background: #fff;
  border: 1px solid #e8eaec;
  border-radius: 4px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.medicine-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-color: #409eff;
}

.medicine-card .name {
  font-weight: 500;
  color: #17233d;
  font-size: 14px;
  margin-bottom: 4px;
}

.medicine-card .spec {
  color: #808695;
  font-size: 12px;
}

.medicine-card .stock {
  color: #19be6b;
  font-size: 12px;
  margin-top: auto;
}

.medicine-card .unit {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #f8f8f9;
  padding: 2px 6px;
  border-radius: 2px;
  font-size: 12px;
  color: #515a6e;
}

.medicine-card.low-stock {
  border-color: #ff9900;
}

.medicine-card.low-stock .stock {
  color: #ff9900;
}

.medicine-card.out-of-stock {
  border-color: #ed4014;
}

.medicine-card.out-of-stock .stock {
  color: #ed4014;
}

/* 添加问诊完成按钮样式 */
.complete-consultation-button {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.complete-consultation-button .ivu-btn {
  min-width: 120px;
}

/* 建议卡片样式 */
.suggestion-card {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  margin: 12px 0;
  padding: 16px;
}

.suggestion-card .suggestion-title {
  font-weight: 500;
  color: #17233d;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.suggestion-card .suggestion-title i {
  margin-right: 8px;
  font-size: 18px;
  color: #2d8cf0;
}

.suggestion-card .suggestion-content {
  color: #515a6e;
  line-height: 1.6;
  margin-bottom: 16px;
  white-space: pre-wrap;
}

.suggestion-card .suggestion-actions {
  display: flex;
  justify-content: flex-end;
}

.adopt-btn {
  display: inline-flex;
  align-items: center;
  padding: 6px 15px;
  background: #2d8cf0;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.adopt-btn i {
  margin-right: 4px;
  font-size: 16px;
}

.adopt-btn:hover {
  background: #5cadff;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(45, 140, 240, 0.2);
}

.adopt-btn:active {
  background: #2b85e4;
  transform: translateY(0);
}

.recovery-advice-section {
  margin: 20px 0;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #17233d;
}

.advice-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.advice-item {
  border: 1px solid #e8eaec;
  padding: 16px;
}

.advice-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.empty-advice {
  text-align: center;
  padding: 32px;
  color: #909399;
}

.empty-advice p {
  margin-top: 8px;
  font-size: 14px;
}

.advice-container {
  width: 100%;
}

.advice-header {
  margin-bottom: 16px;
}

.advice-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.advice-item {
  background: #fff;
  border: 1px solid #dcdee2;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.empty-advice {
  text-align: center;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 4px;
  color: #909399;
}

.empty-advice p {
  margin-top: 8px;
  font-size: 14px;
}

/* 确保输入框和按钮样式与其他表单元素一致 */
.advice-item .ivu-input {
  width: 100%;
}

.advice-item .ivu-select {
  width: 100%;
}

.advice-item .ivu-btn {
  width: 100%;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin: 20px 0;
  padding: 20px 0;
}

.medical-form {
  padding-bottom: 60px; /* 为底部按钮预留空间 */
}

.medical-tabs {
  height: calc(100vh - 200px);
  overflow-y: auto;
  padding: 20px;
}

/* 修改问诊完成按钮的样式 */
.complete-consultation-button {
  margin-top: 20px;
  padding: 20px 0;
  text-align: center;
  border-top: 1px solid #ebeef5;
}

/* 添加建议按钮样式 */
.add-advice-button {
  height: 36px !important;
  font-size: 14px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.add-advice-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 底部按钮组样式 */
.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin: 20px 0;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
}

.action-button {
  min-width: 120px;
  height: 36px !important;
  font-size: 14px !important;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.action-button i {
  margin-right: 4px;
  font-size: 16px;
}

.action-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-button.primary {
  background: #2d8cf0;
  color: white;
  border-color: #2d8cf0;
}

.action-button.info {
  background: #2db7f5;
  color: white;
  border-color: #2db7f5;
}

.action-button.success {
  background: #19be6b;
  color: white;
  border-color: #19be6b;
}

/* 完成问诊按钮容器 */
.complete-consultation-button {
  text-align: center;
  margin-top: 20px;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
}

/* 确保表单内容不会被按钮遮挡 */
.medical-form {
  padding-bottom: 180px; /* 为底部按钮预留更多空间 */
}

.medical-tabs {
  height: calc(100vh - 200px);
  overflow-y: auto;
  padding: 20px;
}

.patient-list {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.patient-list .ivu-table {
  font-size: 14px;
}
.patient-list .ivu-table th, 
.patient-list .ivu-table td {
  padding: 6px 8px;
  text-align: center;
}
</style> 

<template>
  <div class="medical-record">
    <Row :gutter="20">
      <!-- 左侧病历区域 -->
      <Col span="18">
        <Card class="record-card">
          <!-- 顶部患者信息栏 -->
          <div class="patient-info">
            <Row :gutter="16">
              <Col span="8" v-for="(value, key) in patientInfo" :key="key">
                <div class="info-item">
                  <span class="label">{{ key }}：</span>
                  <span class="value">{{ value }}</span>
                </div>
              </Col>
            </Row>
          </div>

          <!-- 标签导航 -->
          <Tabs v-model="activeTab" class="medical-tabs">
            <TabPane label="写病历" name="写病历">
              <Form :model="form" :label-width="120" class="medical-form">
                <!-- 诊断行 -->
                <FormItem label="诊断">
                  <Row :gutter="8">
                    <Col span="4">
                      <Select v-model="form.diagnosisType" style="width: 100%">
                        <Option value="西医">西医</Option>
                        <Option value="中医">中医</Option>
                      </Select>
                    </Col>
                    <Col span="20">
                      <Input 
                        v-model="form.diagnosisName"
                        placeholder="输入诊断名称"
                        @on-change="updateDiagnosisCode"
                      />
                    </Col>
                  </Row>
                </FormItem>

                <!-- 主诉 -->
                <FormItem label="主诉">
                  <Input v-model="form.chiefComplaint" placeholder="请输入患者主诉"/>
                </FormItem>

                <!-- 现病史 -->
                <FormItem label="现病史">
                  <Input 
                    v-model="form.presentIllness" 
                    type="textarea" 
                    :rows="4"
                    placeholder="详细描述现病史"
                  />
                </FormItem>

                <!-- 查体 -->
                <FormItem label="查体">
                  <Input v-model="form.physicalExam" placeholder="输入查体结果"/>
                </FormItem>

                <!-- 辅助检查 -->
                <FormItem label="辅助检查">
                  <Input v-model="form.auxiliaryExam" placeholder="输入辅助检查结果"/>
                </FormItem>

                <!-- 诊疗计划 -->
                <FormItem label="诊疗计划">
                  <Input 
                    v-model="form.treatmentPlan" 
                    type="textarea" 
                    :rows="6"
                    placeholder="制定诊疗计划"
                  />
                </FormItem>

                <!-- 康复建议 -->
                <FormItem label="康复建议">
                  <Row gutter={16}>
                    <Col span="6">
                      <Select v-model="form.adviceType" placeholder="请选择建议类型">
                        <Option value="DIET">饮食建议</Option>
                        <Option value="EXERCISE">运动建议</Option>
                        <Option value="LIFESTYLE">生活方式</Option>
                        <Option value="OTHER">其他建议</Option>
                      </Select>
                    </Col>
                    <Col span="18">
                      <Input v-model="form.adviceContent" type="textarea" :rows="3" placeholder="请输入康复建议内容" />
                    </Col>
                  </Row>
                </FormItem>

                <!-- 底部按钮组 -->
                <div class="form-actions">
                  <Button 
                    class="action-button primary" 
                    @click="saveRecord"
                  >
                    <Icon type="md-checkmark" />
                    保存病历
                  </Button>
                  <Button 
                    class="action-button info" 
                    @click="showRevisionHistory"
                  >
                    <Icon type="md-time" />
                    修订历史
                  </Button>
                </div>

                <!-- 问诊完成按钮 -->
                <div class="complete-consultation-button">
                  <Button 
                    type="success"
                    class="action-button success" 
                    @click="completeConsultation"
                  >
                    <Icon type="md-checkmark-circle" />
                    问诊完成
                  </Button>
                </div>
              </Form>
            </TabPane>
            <TabPane label="开处方" name="开处方">
              <Form :model="prescriptionForm" :label-width="120" class="prescription-form">
                <!-- 处方类型 -->
                <FormItem label="处方类型">
                  <Select v-model="prescriptionForm.type" style="width: 200px">
                    <Option value="普通处方">普通处方</Option>
                    <Option value="急诊处方">急诊处方</Option>
                    <Option value="儿科处方">儿科处方</Option>
                    <Option value="麻醉处方">麻醉处方</Option>
                  </Select>
                </FormItem>

                <!-- 处方药品列表 -->
                <FormItem label="处方药品">
                  <div class="medicine-list-container">
                  <div v-for="(medicine, index) in prescriptionForm.medicines" :key="index" class="medicine-item">
                      <Row :gutter="8">
                      <Col span="5">
                          <Input 
                            v-model="medicine.medicineName" 
                            placeholder="请输入药品名称搜索" 
                            @on-change="() => searchMedicine(index)"
                            :loading="medicineSearchLoading"
                          />
                          <div class="medicine-suggestions" v-show="medicine.suggestions && medicine.suggestions.length">
                            <div v-for="(suggestion, sIndex) in medicine.suggestions" 
                                 :key="sIndex" 
                                 class="suggestion-item"
                                 @click="selectMedicine(index, suggestion)">
                              {{ suggestion.name || suggestion.medicineName }} - {{ suggestion.specification }}
                            </div>
                          </div>
                      </Col>
                      <Col span="3">
                          <Input v-model="medicine.specification" placeholder="规格" readonly/>
                        </Col>
                        <Col span="2">
                          <Input v-model="medicine.unit" placeholder="单位" readonly/>
                      </Col>
                      <Col span="2">
                          <InputNumber 
                            v-model="medicine.singleDose" 
                            placeholder="单次剂量"
                            :min="0"
                            style="width: 100%"
                            @on-change="() => calculateTotalDose(medicine)"
                          />
                      </Col>
                      <Col span="4">
                          <Select v-model="medicine.frequency" placeholder="用药频次" style="width: 100%" @on-change="() => calculateTotalDose(medicine)">
                            <Option value="每日一次">每日一次</Option>
                            <Option value="每日两次">每日两次</Option>
                            <Option value="每日三次">每日三次</Option>
                            <Option value="每日四次">每日四次</Option>
                          </Select>
                      </Col>
                        <Col span="2">
                          <InputNumber 
                            v-model="medicine.days" 
                            placeholder="天数"
                            :min="1"
                            style="width: 100%"
                            @on-change="() => calculateTotalDose(medicine)"
                          />
                      </Col>
                      <Col span="2">
                          <Input :value="medicine.totalDose" placeholder="总量" readonly/>
                        </Col>
                        <Col span="2">
                          <Button type="error" icon="md-trash" @click="removeMedicine(index)" style="width: 100%"></Button>
                      </Col>
                    </Row>
                      <Row :gutter="8" style="margin-top: 8px">
                        <Col span="22">
                          <Input v-model="medicine.usageMethod" placeholder="请输入用法用量说明"/>
                        </Col>
                      </Row>
                      </div>
                    <Button type="dashed" icon="md-add" @click="addMedicine" long style="margin-top: 16px;">添加药品</Button>
                    </div>
                </FormItem>

                <!-- 常用药品快捷选择 -->
                <FormItem label="常用药品">
                  <div class="frequent-medicines">
                    <div v-for="medicine in frequentMedicines" 
                         :key="medicine.id"
                         class="medicine-card"
                         :class="{
                           'low-stock': medicine.stock <= 100,
                           'out-of-stock': medicine.stock <= 0
                         }"
                         @click="selectMedicine(prescriptionForm.medicines.length - 1, medicine)"
                    >
                      <span class="unit">{{ medicine.unit }}</span>
                      <div class="name">{{ medicine.name }}</div>
                      <div class="spec">规格：{{ medicine.specification }}</div>
                      <div class="stock">库存：{{ medicine.stock || 0 }}</div>
                  </div>
                  </div>
                </FormItem>

                <!-- 用药说明 -->
                <FormItem label="用药说明">
                  <Input 
                    v-model="prescriptionForm.instructions" 
                    type="textarea" 
                    :rows="3"
                    placeholder="请输入用药说明，如：每日三次，饭后服用"
                  />
                </FormItem>

                <!-- 处方备注 -->
                <FormItem label="处方备注">
                  <Input 
                    v-model="prescriptionForm.notes" 
                    type="textarea" 
                    :rows="2"
                    placeholder="请输入处方备注信息"
                  />
                </FormItem>

                <!-- 处方有效期 -->
                <FormItem label="处方有效期">
                  <DatePicker 
                    v-model="prescriptionForm.validityPeriod" 
                    type="daterange" 
                    style="width: 300px"
                    :options="validityOptions"
                  />
                </FormItem>

                <!-- 处方按钮 -->
                <FormItem>
                  <div class="prescription-buttons">
                    <Button 
                      class="prescription-button primary" 
                      @click="savePrescription"
                      :loading="savingPrescription"
                    >
                      <Icon type="md-checkmark" />
                    保存处方
                  </Button>
                    <Button 
                      class="prescription-button success" 
                      @click="editPrescription"
                      :disabled="!prescriptionForm.id"
                    >
                      <Icon type="md-create" />
                      修改处方
                    </Button>
                    <Button 
                      class="prescription-button warning" 
                      @click="clearPrescription"
                    >
                      <Icon type="md-trash" />
                      清空处方
                    </Button>
                    <Button 
                      class="prescription-button success" 
                      @click="printPrescription"
                      :disabled="!prescriptionForm.medicines.length"
                    >
                      <Icon type="md-print" />
                    打印处方
                  </Button>
                  </div>
                </FormItem>
                <!-- 问诊完成按钮单独一行 -->
                <div class="complete-consultation-button">
                  <Button 
                    class="prescription-button primary" 
                    @click="completeConsultation"
                  >
                    <Icon type="md-checkmark-circle" />
                    问诊完成
                  </Button>
                </div>
              </Form>
            </TabPane>
          </Tabs>
        </Card>
      </Col>

      <!-- 右侧智能助手区域 -->
      <Col span="6">
        <Card class="assistant-card">
          <!-- 固定在顶部的区域 -->
          <div class="assistant-fixed-top">
            <div class="assistant-header">
              <i class="ivu-icon ivu-icon-md-medical"></i>
              <span>智能诊疗助手</span>
              <div class="assistant-tools">
                <Tooltip content="用药禁忌查询">
                  <i class="ivu-icon ivu-icon-md-warning" @click="showContraindications"></i>
                </Tooltip>
                <Tooltip content="药品说明书">
                  <i class="ivu-icon ivu-icon-md-book" @click="showMedicineGuide"></i>
                </Tooltip>
                <Tooltip content="诊疗指南">
                  <i class="ivu-icon ivu-icon-md-git-book" @click="showClinicalGuide"></i>
                </Tooltip>
              </div>
            </div>
            
            <!-- 快捷操作区 -->
            <div class="quick-actions">
              <button class="quick-action-btn" @click="quickAction('diagnosis')">
                <i class="ivu-icon ivu-icon-md-medical"></i>
                诊断建议
              </button>
              <button class="quick-action-btn" @click="quickAction('prescription')">
                <i class="ivu-icon ivu-icon-md-list-box"></i>
                处方建议
              </button>
              <button class="quick-action-btn" @click="quickAction('examination')">
                <i class="ivu-icon ivu-icon-md-clipboard"></i>
                检查建议
              </button>
            </div>

            <!-- 患者信息摘要 -->
            <div class="patient-summary">
              <div class="summary-title">患者信息摘要</div>
              <div class="summary-content">
                <p><strong>主诊断：</strong>{{ patientInfo['主诊断'] }}</p>
                <p><strong>年龄：</strong>{{ patientInfo['年龄'] }}岁</p>
                <p><strong>性别：</strong>{{ patientInfo['性别'] }}</p>
              </div>
            </div>
          </div>

          <!-- 聊天内容区域 -->
          <div class="chat-container" ref="chatContainer">
            <div v-for="(message, index) in chatHistory" :key="index" 
                 :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
              <div class="message-header">
                <span class="message-type">{{ message.type === 'user' ? '医生' : 'AI助手' }}</span>
                <span class="message-time">{{ message.time }}</span>
              </div>
              <div class="message-content">
                <template v-if="message.type === 'ai' && message.isStreaming">
                  <span v-for="(char, charIndex) in message.content" 
                        :key="charIndex" 
                        class="streaming-char">{{ char }}</span>
                  <div v-if="message.isTyping" class="typing-indicator">
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                    <div class="typing-dot"></div>
                  </div>
                </template>
                <template v-else>
                  <div v-html="formatMessage(message.content)"></div>
                </template>
              </div>
            </div>
          </div>

          <!-- 固定在底部的输入区域 -->
          <div class="input-section">
            <div class="input-wrapper">
              <Input
                v-model="assistantInput"
                type="textarea"
                :rows="3"
                placeholder="输入问题，获取诊疗建议... (Ctrl + Enter 发送)"
                @keyup.enter.ctrl="sendMessage"
              />
            </div>
            <div class="input-actions">
              <Button type="primary" @click="sendMessage" :loading="isLoading">
                发送
              </Button>
              <Button type="text" @click="clearChat">
                清空对话
              </Button>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 修订历史对话框 -->
    <Modal
      v-model="showRevisionHistoryModal"
      title="病历修订历史"
      width="800"
      :mask-closable="true"
    >
      <div class="revision-history">
        <Timeline>
          <TimelineItem v-for="(revision, index) in revisionHistory" :key="index">
            <p class="revision-time">修订时间：{{ formatDateTime(revision.modifiedTime) }}</p>
            <p class="revision-user">修订人：{{ revision.modifiedBy }}</p>
            <div class="revision-content">
              <p class="content-title">修改内容：</p>
              <div class="content-diff">
                <div class="original-content">
                  <p class="diff-title">原内容：</p>
                  <p class="diff-text">{{ revision.oldValue }}</p>
  </div>
                <div class="revised-content">
                  <p class="diff-title">修改后：</p>
                  <p class="diff-text">{{ revision.newValue }}</p>
                </div>
              </div>
              <p class="revision-detail">修改字段：{{ revision.fieldName }}</p>
              <p class="revision-summary">修改说明：{{ revision.revisionContent }}</p>
            </div>
          </TimelineItem>
        </Timeline>
        <div v-if="revisionHistory.length === 0" class="empty-tip">
          <Icon type="md-information-circle" size="24" style="color: #909399;" />
          <p style="color: #606266; margin-top: 10px;">暂无修订记录</p>
        </div>
      </div>
      <div slot="footer">
        <Button @click="showRevisionHistoryModal = false">关闭</Button>
      </div>
    </Modal>

    <!-- 患者选择对话框 -->
    <Modal
      v-model="showPatientSelector"
      title="选择患者"
      width="500"
      :mask-closable="false"
      :closable="false"
    >
      <div class="patient-selector">
        <div class="search-bar" style="display: flex; justify-content: center; align-items: center; gap: 8px;">
          <Input 
            v-model="patientSearchKey" 
            placeholder="请输入患者姓名或档案号"
            search
            @on-search="searchPatients"
            style="width: 180px;"
          />
          <Button type="primary" size="small" @click="searchPatients" :loading="loadingPatients">
            <Icon type="md-search" /> 搜索
          </Button>
        </div>
        <div class="patient-list" style="margin-top: 10px;">
          <Table :loading="loadingPatients" :columns="patientColumns" :data="patientList">
            <template slot-scope="{ row }" slot="action">
              <Button type="primary" size="small" @click="selectPatient(row)" style="padding: 0 12px;">选择</Button>
            </template>
          </Table>
        </div>
        <div class="empty-tip" v-if="patientList.length === 0 && !loadingPatients" style="text-align: center; padding: 20px 0;">
          <Icon type="md-information-circle" size="24" style="color: #909399;" />
          <p style="color: #606266; margin-top: 10px;">
            {{ patientSearchKey ? '未找到匹配的患者' : '请输入患者信息进行搜索' }}
          </p>
        </div>
      </div>
      <div slot="footer">
        <Button @click="closePatientSelector" style="margin-left: 10px;">
          返回
        </Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { getMedicalRecord, updateMedicalRecord, getMedicalRecordByConsultation, createMedicalRecord, getCurrentMedicalRecord } from '@/api/medical-record'
import { getRequest, postRequest, putRequest } from '@/libs/axios'
import { searchPatients, createPatient } from '@/api/patient'
import { createPrescription, getMedicineList, getFrequentMedicines, getPrescriptionsByMedicalRecordId, updatePrescription } from '@/api/prescription'
import { updatePatientStatus } from '@/api/medical-dashboard'
import { assistantChat, analyzeCase, checkContraindications, getMedicineGuide, getClinicalGuide } from '@/api/consultation'

export default {
  name: 'MedicalRecord',
  data() {
    return {
      activeTab: '写病历',
      patientInfo: {
        '门诊类型': '普通门诊',
        '患者姓名': '',
        '性别': '',
        '年龄': '',
        '患者档案号': '',
        '门诊号': '',
        '主诊断': ''
      },
      form: {
        diagnosisType: '西医',
        diagnosisName: '',
        diagnosisCode: '',
        chiefComplaint: '',
        presentIllness: '',
        physicalExam: '',
        auxiliaryExam: '',
        treatmentPlan: '',
        adviceType: '', // 建议类型
        adviceContent: '' // 建议内容
      },
      prescriptionForm: {
        type: '普通处方',
        medicines: [],
        instructions: '',
        notes: '',
        validityPeriod: [],
        medicalRecordId: '',
        patientId: '',
        doctorId: ''
      },
      validityOptions: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 8.64e7;
        }
      },
      chatHistory: [],
      assistantInput: '',
      isLoading: false,
      recordId: null,
      consultationId: null,
      patientId: null,
      doctorName: '', // 添加医生姓名
      orderId: '', // 添加订单ID
      // 患者选择相关
      showPatientSelector: false,
      patientList: [],
      patientSearchKey: '',
      loadingPatients: false,
      patientColumns: [
        { title: '姓名', key: 'name', width: 100 },
        { title: '性别', key: 'gender', width: 60 },
        { title: '操作', slot: 'action', width: 70, align: 'center' }
      ],
      showRevisionHistoryModal: false,
      revisionHistory: [],
      medicineSearchLoading: false,
      frequentMedicines: [],
      medicineSearchTimeout: null
    }
  },
  created() {
    console.log('=== 组件创建 ===');
    console.log('路由参数:', this.$route.query);
    const { patientId, recordId, consultationId } = this.$route.query;
    
    this.patientId = patientId;
    this.recordId = recordId;
    this.consultationId = consultationId;
    
    if (patientId) {
      console.log('加载患者病历:', patientId);
      this.loadPatientMedicalRecord(patientId);
    } else if (recordId) {
      console.log('加载指定病历:', recordId);
      this.loadMedicalRecord();
    } else if (consultationId) {
      console.log('加载问诊病历:', consultationId);
      this.loadMedicalRecordFromConsultation();
    } else {
      console.log('未指定患者或病历ID，显示患者选择框');
      this.showPatientSelector = true;
      this.loadPatientList();
    }
    this.loadFrequentMedicines();

    // 检查是否有暂存的处方
    try {
      const draftData = localStorage.getItem('prescriptionDraft');
      if (draftData) {
        const draft = JSON.parse(draftData);
        if (draft.savedTime) {
          const savedTime = new Date(draft.savedTime);
          const now = new Date();
          const hoursDiff = (now - savedTime) / (1000 * 60 * 60);
          
          if (hoursDiff < 24) { // 如果暂存时间在24小时内
            this.$Modal.confirm({
              title: '发现暂存处方',
              content: `发现${this.formatTimeAgo(savedTime)}暂存的处方，是否加载？`,
              onOk: () => {
                this.loadPrescriptionDraft();
              },
              onCancel: () => {
                this.clearPrescriptionDraft();
              }
            });
          } else {
            // 如果暂存时间超过24小时，自动清除
            this.clearPrescriptionDraft();
          }
        }
      }
    } catch (error) {
      console.error('检查暂存处方失败:', error);
    }
  },
  methods: {
    async loadPatientMedicalRecord(patientId) {
      console.log('=== 开始加载患者病历 ===');
      console.log('参数 - patientId:', patientId);
      this.isLoading = true;
      try {
        console.log('调用getCurrentMedicalRecord API...');
        const response = await getCurrentMedicalRecord(patientId);
        console.log('API响应:', response);
        
        if (response.success && response.result) {
          const record = response.result;
          this.recordId = record.id;
          console.log('病历ID:', this.recordId);
          
          // 更新表单数据
          this.form = {
            diagnosisType: record.diagnosisType || '西医',
            diagnosisName: record.diagnosisName || '',
            diagnosisCode: record.diagnosisCode || '',
            chiefComplaint: record.chiefComplaint || '',
            presentIllness: record.presentIllness || '',
            physicalExam: record.physicalExam || '',
            auxiliaryExam: record.auxiliaryExam || '',
            treatmentPlan: record.treatmentPlan || '',
            adviceType: record.adviceType || '',
            adviceContent: record.adviceContent || ''
          };
          console.log('更新后的表单数据:', this.form);
          
          // 更新患者信息
          this.patientInfo = {
            '门诊类型': record.visitType || '普通门诊',
            '患者姓名': record.patientName || '未知患者',
            '性别': record.gender || '未知',
            '年龄': record.age || '未知',
            '患者档案号': record.patientFileNumber || '未生成',
            '门诊号': record.outpatientNumber || '未生成',
            '主诊断': record.diagnosisName || '待诊断'
          };
          console.log('更新后的患者信息:', this.patientInfo);

          // 加载处方记录
          await this.loadPrescriptions();
          
          this.$Message.success('病历加载成功');
        } else if (response.code === 404) {
          console.warn('未找到病历记录，将创建新病历');
          this.patientInfo = {
            '门诊类型': '普通门诊',
            '患者姓名': '未知患者',
            '性别': '未知',
            '年龄': '未知',
            '患者档案号': '未生成',
            '门诊号': '未生成',
            '主诊断': '待诊断'
          };
          this.$Message.info('未找到病历记录，已创建新病历');
        } else {
          console.error('API返回错误:', response);
          throw new Error(response.message || '加载病历失败');
        }
      } catch (error) {
        console.error('加载病历出错:', error);
        console.error('错误详情:', {
          message: error.message,
          stack: error.stack,
          response: error.response
        });
        this.patientInfo = {
          '门诊类型': '普通门诊',
          '患者姓名': '未知患者',
          '性别': '未知',
          '年龄': '未知',
          '患者档案号': '未生成',
          '门诊号': '未生成',
          '主诊断': '待诊断'
        };
        this.$Message.error('加载病历失败，已使用默认信息');
      } finally {
        this.isLoading = false;
        console.log('=== 病历加载完成 ===');
      }
    },
    async loadMedicalRecord() {
      if (!this.recordId) return;
      
      this.isLoading = true;
      try {
        const response = await getMedicalRecord(this.recordId);
        
        if (response.success && response.result) {
          const record = response.result;
          // 更新表单数据
          this.form = {
            diagnosisType: record.diagnosisType || '西医',
            diagnosisName: record.diagnosisName || '',
            diagnosisCode: record.diagnosisCode || '',
            chiefComplaint: record.chiefComplaint || '',
            presentIllness: record.presentIllness || '',
            physicalExam: record.physicalExam || '',
            auxiliaryExam: record.auxiliaryExam || '',
            treatmentPlan: record.treatmentPlan || '',
            adviceType: record.adviceType || '',
            adviceContent: record.adviceContent || ''
          };
          
          // 更新患者信息
          this.patientInfo = {
            '门诊类型': '普通门诊',
            '患者姓名': record.patientName || '',
            '性别': record.gender || '男',
            '年龄': record.age || 0,
            '患者档案号': record.patientFileNumber || '',
            '门诊号': record.outpatientNumber || '',
            '主诊断': record.diagnosisName || ''
          };

          // 加载处方记录
          await this.loadPrescriptions();
          
          this.$Message.success('病历加载成功');
        } else {
          throw new Error(response.message || '加载病历失败');
        }
      } catch (error) {
        this.$Message.error('加载病历失败，请稍后重试');
        console.error(error);
      } finally {
        this.isLoading = false;
      }
    },
    async loadMedicalRecordFromConsultation() {
      if (!this.consultationId) return;
      
      this.isLoading = true;
      try {
        const response = await getMedicalRecordByConsultation(this.consultationId);
        
        if (response.success && response.result) {
          const record = response.result;
          // 设置recordId，以便后续保存
          this.recordId = record.id;
          
          // 更新表单数据
          this.form = {
            diagnosisType: record.diagnosisType || '西医',
            diagnosisName: record.diagnosisName || '',
            diagnosisCode: record.diagnosisCode || '',
            chiefComplaint: record.chiefComplaint || '',
            presentIllness: record.presentIllness || '',
            physicalExam: record.physicalExam || '',
            auxiliaryExam: record.auxiliaryExam || '',
            treatmentPlan: record.treatmentPlan || '',
            adviceType: record.adviceType || '',
            adviceContent: record.adviceContent || ''
          };
          
          // 更新患者信息
          this.patientInfo = {
            '门诊类型': '普通门诊',
            '患者姓名': record.patientName || '',
            '性别': record.gender || '男',
            '年龄': record.age || 0,
            '患者档案号': record.patientFileNumber || '',
            '门诊号': record.outpatientNumber || '',
            '主诊断': record.diagnosisName || ''
          };

          // 加载处方记录
          await this.loadPrescriptions();
          
          this.$Message.success('病历加载成功');
        } else {
          throw new Error(response.message || '加载病历失败');
        }
      } catch (error) {
        this.$Message.error('加载病历失败，请稍后重试');
        console.error(error);
      } finally {
        this.isLoading = false;
      }
    },
    async saveRecord() {
      console.log('=== 开始保存病历 ===');
      this.isLoading = true;
      try {
        // 准备患者信息
        const patientInfo = {
          patientName: this.patientInfo['患者姓名'] || '',
          gender: this.patientInfo['性别'] || '',
          age: this.patientInfo['年龄'] || 0,
          patientFileNumber: this.patientInfo['患者档案号'] || '',
          outpatientNumber: this.patientInfo['门诊号'] || ''
        };
        console.log('患者信息:', patientInfo);
        
        // 组合病历数据
        const medicalRecord = {
          ...this.form,
          ...patientInfo,
          consultationId: this.consultationId,
          doctorName: this.doctorName
        };

        // 只在创建新病历时设置orderId，更新时不修改orderId
        if (!this.recordId) {
          medicalRecord.orderId = this.orderId;
        }
        
        console.log('准备保存的病历数据:', medicalRecord);
        
        let response;
        if (this.recordId) {
          console.log('更新现有病历, ID:', this.recordId);
          medicalRecord.id = this.recordId;
          response = await updateMedicalRecord(this.recordId, medicalRecord);
        } else {
          console.log('创建新病历');
          response = await createMedicalRecord(medicalRecord);
        }
        
        console.log('保存病历API响应:', response);
        
        if (response.success && response.result) {
          if (!this.recordId) {
            this.recordId = response.result.id;
            console.log('新创建的病历ID:', this.recordId);
          }
          this.$Message.success('病历保存成功');
        } else {
          console.error('API返回错误:', response);
          throw new Error(response.message || '保存病历失败');
        }
      } catch (error) {
        console.error('保存病历错误:', error);
        console.error('错误详情:', {
          message: error.message,
          stack: error.stack,
          response: error.response
        });
        this.$Message.error('保存病历失败，请稍后重试');
      } finally {
        this.isLoading = false;
        console.log('=== 病历保存完成 ===');
      }
    },
    updateDiagnosisCode() {
      const codes = {
        '感冒': 'J00',
        '高血压': 'I10',
        '糖尿病': 'E11',
        '肺炎': 'J18.9'
      };
      this.form.diagnosisCode = codes[this.form.diagnosisName] || '未找到编码';
    },
    formatTime() {
      return new Date().toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    },
    addMessage(content, type) {
      this.chatHistory.push({
        content,
        type,
        time: this.formatTime(),
        isStreaming: false
      });
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
    scrollToBottom() {
      const chatContainer = this.$refs.chatContainer;
      chatContainer.scrollTop = chatContainer.scrollHeight;
    },
    async streamResponse(text) {
      const message = {
        content: '',
        type: 'ai',
        time: this.formatTime(),
        isStreaming: true
      };
      this.chatHistory.push(message);
      
      for (let i = 0; i < text.length; i++) {
        message.content += text[i];
        await new Promise(resolve => setTimeout(resolve, 50));
        this.scrollToBottom();
      }
      
      message.isStreaming = false;
    },
    async sendMessage() {
      if (!this.assistantInput.trim()) return;
      
      this.isLoading = true;
      try {
        // 添加用户消息
        this.addMessage(this.assistantInput, 'user');
        
        // 准备上下文信息
        const context = {
          patientInfo: this.patientInfo,
          medicalRecord: {
            diagnosisType: this.form.diagnosisType,
            diagnosisName: this.form.diagnosisName,
            chiefComplaint: this.form.chiefComplaint,
            presentIllness: this.form.presentIllness,
            physicalExam: this.form.physicalExam,
            auxiliaryExam: this.form.auxiliaryExam,
            treatmentPlan: this.form.treatmentPlan
          },
          prescription: this.prescriptionForm
        };
        
        // 调用AI助手API
        const response = await assistantChat({
          message: this.assistantInput,
          context: context
        });
        
        if (response.success && response.result) {
          await this.streamResponse(response.result);
        } else {
          throw new Error(response.message || '请求失败');
        }
        
      } catch (error) {
        console.error('AI助手请求失败:', error);
        this.$Message.error('请求失败，请稍后重试');
      } finally {
        this.isLoading = false;
        this.assistantInput = '';
      }
    },
    addMedicine() {
      this.prescriptionForm.medicines.push({
        medicineId: '',
        medicineName: '',
        specification: '',
        unit: '',
        singleDose: 1,
        frequency: '每日一次',
        days: 1,
        totalDose: 0,
        usageMethod: '',
        notes: '',
        suggestions: []
      });
    },
    removeMedicine(index) {
      this.prescriptionForm.medicines.splice(index, 1);
    },
    async searchMedicine(index) {
      const medicine = this.prescriptionForm.medicines[index];
      if (!medicine.medicineName || medicine.medicineName.trim().length < 1) {
        medicine.suggestions = [];
        return;
      }

      // 防抖处理，延长到800ms
      if (this.medicineSearchTimeout) {
        clearTimeout(this.medicineSearchTimeout);
      }

      this.medicineSearchTimeout = setTimeout(async () => {
        this.medicineSearchLoading = true;
        try {
          const trimmedName = medicine.medicineName.trim();
          console.log('开始搜索药品，关键词:', trimmedName);
          const response = await getMedicineList(trimmedName);
          console.log('搜索药品API响应:', response);
          
          if (response && response.success) {
            // 确保返回的数据格式正确
            medicine.suggestions = (response.result || []).map(item => ({
              id: item.id,
              name: item.name,
              specification: item.specification,
              unit: item.unit,
              stock: Number(item.stock) || 0,
              price: Number(item.price) || 0,
              manufacturer: item.manufacturer || '',
              category: item.category || ''
            }));
            
            console.log('搜索结果数量:', medicine.suggestions.length);
            
            if (medicine.suggestions.length === 0) {
              this.$Message.info({
                content: '未找到匹配的药品',
                duration: 3
              });
            }
      } else {
            console.warn('API返回错误:', response);
        medicine.suggestions = [];
            this.$Message.warning({
              content: (response && response.message) || '搜索药品失败',
              duration: 3
            });
          }
        } catch (error) {
          console.error('搜索药品异常:', error);
          medicine.suggestions = [];
          this.$Message.error({
            content: '搜索失败，请重试',
            duration: 3
          });
        } finally {
          this.medicineSearchLoading = false;
        }
      }, 800);
    },
    selectMedicine(index, suggestion) {
      console.log('选择药品:', suggestion);
      
      // 如果当前索引超出数组范围，先添加一个新的药品
      if (index >= this.prescriptionForm.medicines.length) {
        this.addMedicine();
        index = this.prescriptionForm.medicines.length - 1;
      }
      
      const medicine = this.prescriptionForm.medicines[index];
      // 设置药品基本信息
      medicine.medicineId = suggestion.id || suggestion.medicineId;
      medicine.medicineName = suggestion.name || suggestion.medicineName;
      medicine.specification = suggestion.specification;
      medicine.unit = suggestion.unit;
      
      // 设置默认值
      medicine.singleDose = medicine.singleDose || 1;
      medicine.frequency = medicine.frequency || '每日一次';
      medicine.days = medicine.days || 1;
      
      // 清空建议列表
      medicine.suggestions = [];
      
      // 计算总量
      this.calculateTotalDose(medicine);
      
      console.log('更新后的药品信息:', medicine);
    },
    calculateTotalDose(medicine) {
      console.log('计算总量:', medicine);
      if (!medicine.singleDose || !medicine.frequency || !medicine.days) {
        medicine.totalDose = 0;
        return;
      }

      const frequencyMap = {
        '每日一次': 1,
        '每日两次': 2,
        '每日三次': 3,
        '每日四次': 4
      };
      
      const times = frequencyMap[medicine.frequency] || 1;
      medicine.totalDose = medicine.singleDose * times * medicine.days;
      console.log('计算结果:', medicine.totalDose);
    },
    async savePrescription() {
      if (!this.prescriptionForm.medicines.length) {
        this.$Message.warning('请至少添加一个药品');
        return;
      }

      // 设置处方关联信息
      this.prescriptionForm.medicalRecordId = this.recordId;
      this.prescriptionForm.patientId = this.patientId;
      this.prescriptionForm.doctorId = this.$store.state.user.userId;

      try {
        const response = await createPrescription(this.prescriptionForm);
        if (response.success) {
          this.$Message.success('处方保存成功');
          // 不清空表单，保留当前数据
          // 记录已保存的处方ID
          this.prescriptionForm.id = response.result;
        } else {
          this.$Message.error(response.message || '保存失败');
        }
      } catch (error) {
        console.error('保存处方失败:', error);
        this.$Message.error('保存处方失败，请重试');
      }
    },
    // 暂存处方
    savePrescriptionDraft() {
      if (!this.prescriptionForm.medicines.length) {
        this.$Message.warning('请至少添加一个药品');
        return;
      }
      
      try {
        // 将处方数据保存到localStorage
        const draftData = {
          ...this.prescriptionForm,
          savedTime: new Date().toISOString(),
          medicalRecordId: this.recordId,
          patientId: this.patientId
        };
        
        localStorage.setItem('prescriptionDraft', JSON.stringify(draftData));
        this.$Message.success('处方已暂存');
      } catch (error) {
        console.error('暂存处方失败:', error);
        this.$Message.error('暂存处方失败');
      }
    },

    // 加载暂存的处方
    loadPrescriptionDraft() {
      try {
        const draftData = localStorage.getItem('prescriptionDraft');
        if (draftData) {
          const draft = JSON.parse(draftData);
          // 检查是否是当前病历的处方
          if (draft.medicalRecordId === this.recordId && draft.patientId === this.patientId) {
            this.prescriptionForm = draft;
            this.$Message.success('已加载暂存的处方');
          } else {
            this.$Message.warning('暂存的处方不属于当前病历，已忽略');
          }
        }
      } catch (error) {
        console.error('加载暂存处方失败:', error);
        this.$Message.error('加载暂存处方失败');
      }
    },

    // 清空暂存的处方
    clearPrescription() {
      this.$Modal.confirm({
        title: '确认清空',
        content: '确定要清空当前处方吗？此操作不可恢复。',
        onOk: () => {
          this.prescriptionForm = {
            type: '普通处方',
            medicines: [],
            instructions: '',
            notes: '',
            validityPeriod: [],
            medicalRecordId: this.recordId,
            patientId: this.patientId,
            doctorId: this.$store.state.user.userId
          };
          this.$Message.success('处方已清空');
        }
      });
    },

    // 修改处方
    async editPrescription() {
      if (!this.prescriptionForm.id) {
        this.$Message.warning('请先保存处方');
        return;
      }

      try {
        // 准备请求数据
        const prescriptionDTO = {
          id: this.prescriptionForm.id,
          medicalRecordId: this.recordId,
          patientId: this.patientId,
          doctorId: this.$store.state.user.userId,
          prescriptionType: this.prescriptionForm.type,
          instructions: this.prescriptionForm.instructions,
          notes: this.prescriptionForm.notes,
          validityStartTime: this.prescriptionForm.validityPeriod[0],
          validityEndTime: this.prescriptionForm.validityPeriod[1],
          medicines: this.prescriptionForm.medicines.map(medicine => ({
            medicineId: medicine.medicineId,
            medicineName: medicine.medicineName,
            specification: medicine.specification,
            unit: medicine.unit,
            amount: medicine.amount,
            usageMethod: medicine.usageMethod,
            frequency: medicine.frequency,
            days: medicine.days,
            singleDose: medicine.singleDose,
            totalDose: medicine.totalDose,
            notes: medicine.notes
          }))
        };

        const response = await updatePrescription(prescriptionDTO);
        if (response.success) {
          this.$Message.success('处方修改成功');
          // 重新加载处方列表
          await this.loadPrescriptions();
        } else {
          this.$Message.error(response.message || '修改失败');
        }
      } catch (error) {
        console.error('修改处方失败:', error);
        this.$Message.error('修改处方失败，请重试');
      }
    },
    printPrescription() {
      if (!this.prescriptionForm.medicines.length) {
        this.$Message.warning('请先添加药品');
        return;
      }

      try {
        // 这里可以调用打印服务
        window.print();
      } catch (error) {
        console.error('打印处方失败:', error);
        this.$Message.error('打印失败，请重试');
      }
    },
    formatMessage(content) {
      if (!content) return '';
      
      // 使用marked库处理Markdown
      let formatted = content;
      
      // 处理建议块
      formatted = formatted.replace(/【建议】(.*?)【\/建议】/g, (match, p1) => {
        let icon = 'md-medical';
        let title = '诊断建议';
        
        if (p1.includes('处方')) {
          icon = 'md-list-box';
          title = '处方建议';
        } else if (p1.includes('检查')) {
          icon = 'md-clipboard';
          title = '检查建议';
        }
        
        return `<div class="suggestion-card">
          <div class="suggestion-title">
            <i class="ivu-icon ivu-icon-${icon}"></i>
            ${title}
          </div>
          <div class="suggestion-content">${p1}</div>
          <div class="suggestion-actions">
            <button class="adopt-btn" onclick="adoptSuggestion('${encodeURIComponent(p1)}')">
              <i class="ivu-icon ivu-icon-md-checkmark"></i>
              采纳建议
            </button>
          </div>
        </div>`;
      });
      
      // 处理代码块
      formatted = formatted.replace(/```(.*?)\n([\s\S]*?)```/g, (match, lang, code) => {
        return `<pre><code class="language-${lang}">${this.escapeHtml(code.trim())}</code></pre>`;
      });
      
      // 处理行内代码
      formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>');
      
      // 处理标题
      formatted = formatted.replace(/#{1,6} ([^\n]+)/g, (match, content) => {
        const level = match.match(/^#+/)[0].length;
        return `<h${level}>${content.trim()}</h${level}>`;
      });
      
      // 处理列表
      formatted = formatted.replace(/^\s*[-*+]\s+([^\n]+)/gm, '<li>$1</li>');
      formatted = formatted.replace(/(<li>.*?<\/li>)\s*(?=<li>|$)/gs, '<ul>$1</ul>');
      
      // 处理有序列表
      formatted = formatted.replace(/^\s*\d+\.\s+([^\n]+)/gm, '<li>$1</li>');
      formatted = formatted.replace(/(<li>.*?<\/li>)\s*(?=<li>|$)/gs, '<ol>$1</ol>');
      
      // 处理粗体
      formatted = formatted.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
      
      // 处理斜体
      formatted = formatted.replace(/\*([^*]+)\*/g, '<em>$1</em>');
      
      // 处理引用
      formatted = formatted.replace(/^\s*>\s*([^\n]+)/gm, '<blockquote>$1</blockquote>');
      
      // 处理换行
      formatted = formatted.replace(/\n/g, '<br>');
      
      return formatted;
    },
    
    escapeHtml(text) {
      const div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
    },
    async showContraindications() {
      if (!this.prescriptionForm.medicines.length) {
        this.$Message.warning('请先添加药品');
        return;
      }

      try {
        this.isLoading = true;
        this.addMessage('正在查询用药禁忌信息...', 'user');

        const response = await checkContraindications({
          medicines: this.prescriptionForm.medicines.map(m => ({
            id: m.medicineId,
            name: m.medicineName
          })),
          patientInfo: this.patientInfo
        });

        if (response.success && response.result) {
          await this.streamResponse(response.result);
        } else {
          throw new Error(response.message || '查询失败');
        }
      } catch (error) {
        console.error('查询用药禁忌失败:', error);
        this.$Message.error('查询失败，请稍后重试');
      } finally {
        this.isLoading = false;
      }
    },
    async showMedicineGuide() {
      if (!this.prescriptionForm.medicines.length) {
        this.$Message.warning('请先添加药品');
        return;
      }

      try {
        this.isLoading = true;
        this.addMessage('正在查询药品说明书...', 'user');

        const response = await getMedicineGuide({
          medicines: this.prescriptionForm.medicines.map(m => ({
            id: m.medicineId,
            name: m.medicineName
          }))
        });

        if (response.success && response.result) {
          await this.streamResponse(response.result);
        } else {
          throw new Error(response.message || '查询失败');
        }
      } catch (error) {
        console.error('查询药品说明书失败:', error);
        this.$Message.error('查询失败，请稍后重试');
      } finally {
        this.isLoading = false;
      }
    },
    async showClinicalGuide() {
      if (!this.form.diagnosisName) {
        this.$Message.warning('请先填写诊断');
        return;
      }

      try {
        this.isLoading = true;
        this.addMessage('正在查询诊疗指南...', 'user');

        const response = await getClinicalGuide({
          diagnosis: this.form.diagnosisName,
          diagnosisType: this.form.diagnosisType
        });

        if (response.success && response.result) {
          await this.streamResponse(response.result);
        } else {
          throw new Error(response.message || '查询失败');
        }
      } catch (error) {
        console.error('查询诊疗指南失败:', error);
        this.$Message.error('查询失败，请稍后重试');
      } finally {
        this.isLoading = false;
      }
    },
    async quickAction(type) {
      const templates = {
        diagnosis: {
          title: '诊断建议',
          analyze: async () => {
            const context = {
              chiefComplaint: this.form.chiefComplaint,
              presentIllness: this.form.presentIllness,
              physicalExam: this.form.physicalExam
            };
            
            const response = await analyzeCase({
              message: '请根据以下信息给出诊断建议：\n' +
                      `主诉：${context.chiefComplaint || '无'}\n` +
                      `现病史：${context.presentIllness || '无'}\n` +
                      `体格检查：${context.physicalExam || '无'}`,
              context: context
            });
            
            if (response.success && response.result) {
              return response.result;
            }
            throw new Error(response.message || '分析失败');
          }
        },
        prescription: {
          title: '处方建议',
          analyze: async () => {
            const context = {
              diagnosisName: this.form.diagnosisName,
              chiefComplaint: this.form.chiefComplaint,
              presentIllness: this.form.presentIllness
            };
            
            const response = await analyzeCase({
              message: '请根据以下信息给出处方建议：\n' +
                      `诊断：${context.diagnosisName || '无'}\n` +
                      `主诉：${context.chiefComplaint || '无'}\n` +
                      `现病史：${context.presentIllness || '无'}`,
              context: context
            });
            
            if (response.success && response.result) {
              return response.result;
            }
            throw new Error(response.message || '分析失败');
          }
        },
        examination: {
          title: '检查建议',
          analyze: async () => {
            const context = {
              diagnosisName: this.form.diagnosisName,
              chiefComplaint: this.form.chiefComplaint,
              presentIllness: this.form.presentIllness,
              physicalExam: this.form.physicalExam
            };
            
            const response = await analyzeCase({
              message: '请根据以下信息给出检查建议：\n' +
                      `诊断：${context.diagnosisName || '无'}\n` +
                      `主诉：${context.chiefComplaint || '无'}\n` +
                      `现病史：${context.presentIllness || '无'}\n` +
                      `体格检查：${context.physicalExam || '无'}`,
              context: context
            });
            
            if (response.success && response.result) {
              return response.result;
            }
            throw new Error(response.message || '分析失败');
          }
        }
      };

      try {
        this.isLoading = true;
        const template = templates[type];
        if (!template) return;

        this.addMessage(`请求${template.title}...`, 'user');
        const result = await template.analyze();
        await this.streamResponse(result);
      } catch (error) {
        console.error(`${templates[type].title}请求失败:`, error);
        this.$Message.error('请求失败，请稍后重试');
      } finally {
        this.isLoading = false;
      }
    },
    clearChat() {
      this.chatHistory = [];
    },
    // 患者选择相关
    async loadPatientList() {
      this.loadingPatients = true;
      
      try {
        // 调用API获取患者列表
        const response = await getRequest('/patients/search');
        console.log('患者列表查询结果:', response);
        
        if (response && response.success && response.result && response.result.length > 0) {
          // 补全id字段
          this.patientList = response.result.map(item => ({
            ...item,
            id: item.id || item.fileNumber
          }));
          console.log('成功获取患者列表，数量:', this.patientList.length);
        } else {
          console.warn('API返回空数据或错误:', response);
          // 如果API无数据，提示用户
          this.$Message.warning('未获取到患者数据，请联系管理员');
          this.patientList = [];
        }
      } catch (error) {
        console.error('加载患者列表异常:', error);
        this.$Message.error('获取患者列表失败: ' + (error.message || '未知错误'));
        this.patientList = [];
      } finally {
        this.loadingPatients = false;
      }
    },
    
    async searchPatients() {
      if (!this.patientSearchKey.trim()) {
        this.loadPatientList();
        return;
      }
      
      this.loadingPatients = true;
      
      try {
        // 调用API搜索患者
        const response = await getRequest(`/patients/search?keyword=${encodeURIComponent(this.patientSearchKey)}`);
        console.log('患者搜索API结果:', response);
        
        if (response && response.success && response.result) {
          // 补全id字段
          this.patientList = response.result.map(item => ({
            ...item,
            id: item.id || item.fileNumber
          }));
          console.log('成功搜索患者，数量:', this.patientList.length);
          
          if (this.patientList.length === 0) {
            this.$Message.info('未找到匹配的患者');
          }
        } else {
          console.warn('搜索API返回错误:', response);
          this.$Message.warning('搜索患者失败，请稍后重试');
          this.patientList = [];
        }
      } catch (error) {
        console.error('搜索患者异常:', error);
        this.$Message.error('搜索患者失败: ' + (error.message || '未知错误'));
        this.patientList = [];
      } finally {
        this.loadingPatients = false;
      }
    },
    
    async selectPatient(patient) {
      console.log('选择患者:', patient);
      this.patientId = patient.id || patient.fileNumber;
      if (!this.patientId) {
        this.$Message.error('患者信息缺失，无法加载病历');
        return;
      }
      this.showPatientSelector = false;
      // 1. 先查该患者的最新挂号单
      try {
        const orderRes = await getRequest('/hospitalOrder/getLatestByPatientId', { patientId: this.patientId });
        if (!orderRes.success || !orderRes.result) {
          this.$Message.error('未找到该患者的挂号记录，请重新选择患者');
          this.showPatientSelector = true;
          return;
        }
        const orderId = orderRes.result.id;
        // 2. 再查病历
        await this.loadPatientMedicalRecord(orderId);
        // 检查是否加载到病历
        if (!this.recordId) {
          this.$Message.error('未查到该患者的病历，请重新选择患者');
          this.showPatientSelector = true;
        }
      } catch (error) {
        console.error('获取挂号记录失败:', error);
        this.$Message.error('获取挂号记录失败，请稍后重试');
        this.showPatientSelector = true;
      }
    },
    
    createNewPatient() {
      // 此处应该跳转到创建患者页面或打开创建患者的对话框
      this.$Message.info('创建新患者功能尚未实现，将使用默认患者');
      
      // 使用一个默认患者
      const defaultPatient = { 
        id: '1909561293300436992', 
        name: '新患者',
        gender: '男',
        age: 30
      };
      
      this.selectPatient(defaultPatient);
    },
    
    closePatientSelector() {
      // 关闭对话框
      this.showPatientSelector = false;
      // 使用浏览器历史返回功能而不是固定路径
      this.$router.go(-1);
    },
    async showRevisionHistory() {
      if (!this.recordId) {
        this.$Message.warning('请先保存病历');
        return;
      }

      this.showRevisionHistoryModal = true;
      try {
        const response = await getRequest(`/medical-record-revisions/${this.recordId}`);
        if (response.success && response.result) {
          this.revisionHistory = response.result;
        } else {
          this.$Message.error('获取修订历史失败');
        }
      } catch (error) {
        console.error('获取修订历史失败:', error);
        this.$Message.error('获取修订历史失败');
      }
    },
    formatDateTime(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },
    async loadFrequentMedicines() {
      try {
        const response = await getFrequentMedicines();
        if (response.success) {
          this.frequentMedicines = response.result;
        }
      } catch (error) {
        console.error('加载常用药品失败:', error);
      }
    },
    // 添加一个格式化时间的方法
    formatTimeAgo(date) {
      const now = new Date();
      const diff = now - date;
      const minutes = Math.floor(diff / (1000 * 60));
      const hours = Math.floor(minutes / 60);
      
      if (hours > 0) {
        return `${hours}小时前`;
      } else if (minutes > 0) {
        return `${minutes}分钟前`;
      } else {
        return '刚刚';
      }
    },
    // 加载处方记录
    async loadPrescriptions() {
      if (!this.recordId) {
        console.warn('没有病历ID，无法加载处方记录');
        return;
      }

      try {
        console.log('开始加载处方记录, 病历ID:', this.recordId);
        const response = await getPrescriptionsByMedicalRecordId(this.recordId);
        console.log('处方记录加载响应:', response);

        if (response.success && response.result && response.result.length > 0) {
          // 获取最新的处方记录
          const latestPrescription = response.result[0];
          console.log('最新处方记录:', latestPrescription);

          // 确保药品列表数据格式正确
          const medicines = (latestPrescription.prescriptionDetails || []).map(detail => ({
            medicineId: detail.medicineId,
            medicineName: detail.medicineName,
            specification: detail.specification,
            unit: detail.unit,
            amount: detail.amount,
            usageMethod: detail.usageMethod,
            frequency: detail.frequency,
            days: detail.days,
            singleDose: detail.singleDose,
            totalDose: detail.totalDose,
            notes: detail.notes
          }));

          this.prescriptionForm = {
            id: latestPrescription.id,
            type: latestPrescription.prescriptionType || '普通处方',
            medicines: medicines,
            instructions: latestPrescription.instructions || '',
            notes: latestPrescription.notes || '',
            validityPeriod: [
              latestPrescription.validityStartTime,
              latestPrescription.validityEndTime
            ],
            medicalRecordId: this.recordId,
            patientId: this.patientId,
            doctorId: this.$store.state.user.userId
          };
          console.log('处方表单已更新:', this.prescriptionForm);
        } else {
          // 如果没有处方记录，初始化一个空的处方表单
          this.prescriptionForm = {
            type: '普通处方',
            medicines: [],
            instructions: '',
            notes: '',
            validityPeriod: [],
            medicalRecordId: this.recordId,
            patientId: this.patientId,
            doctorId: this.$store.state.user.userId
          };
          console.log('初始化空处方表单:', this.prescriptionForm);
        }
      } catch (error) {
        console.error('加载处方记录失败:', error);
        this.$Message.error('加载处方记录失败');
      }
    },
    async completeConsultation() {
      try {
        // 先保存当前病历
        await this.saveRecord();
        
        // 如果有处方且未保存，提示保存处方
        if (this.prescriptionForm.medicines.length > 0 && !this.prescriptionForm.id) {
          this.$Modal.confirm({
            title: '保存处方',
            content: '您有未保存的处方，是否保存？',
            onOk: async () => {
              await this.savePrescription();
              await this.updateStatus();
            },
            onCancel: async () => {
              await this.updateStatus();
            }
          });
        } else {
          await this.updateStatus();
        }
      } catch (error) {
        console.error('完成问诊失败:', error);
        this.$Message.error('完成问诊失败，请重试');
      }
    },
    async updateStatus() {
      try {
        const userId = this.$store.state.user.userId;
        const response = await updatePatientStatus(userId, this.patientId, 'COMPLETED');
        
        if (response.success) {
          this.$Message.success('问诊已完成');
          // 返回医生工作台
          this.$router.push({
            name: 'doctorDashboard'
          });
        } else {
          throw new Error(response.message || '更新状态失败');
        }
      } catch (error) {
        console.error('更新患者状态失败:', error);
        this.$Message.error('更新患者状态失败，请重试');
      }
    },
    // 采纳建议
    adoptSuggestion(suggestion) {
      try {
        suggestion = decodeURIComponent(suggestion);
        
        // 根据建议内容类型,填充到相应表单
        if (suggestion.includes('诊断')) {
          this.form.diagnosisName = suggestion.match(/诊断：(.*)/)[1];
        } else if (suggestion.includes('处方')) {
          // 解析处方建议并添加到处方列表
          const medicine = this.parseMedicineSuggestion(suggestion);
          if (medicine) {
            this.prescriptionForm.medicines.push(medicine);
          }
        } else if (suggestion.includes('检查')) {
          this.form.auxiliaryExam = suggestion;
        }
        
        this.$Message.success('已采纳建议');
      } catch (error) {
        console.error('采纳建议失败:', error);
        this.$Message.error('采纳建议失败');
      }
    },
    parseMedicineSuggestion(suggestion) {
      // 解析处方建议文本,提取药品信息
      const regex = /药品：(.*?)，规格：(.*?)，用法：(.*)/;
      const match = suggestion.match(regex);
      if (match) {
        return {
          medicineName: match[1],
          specification: match[2],
          usageMethod: match[3],
          // 其他字段设置默认值
          unit: '盒',
          singleDose: 1,
          frequency: '每日一次',
          days: 1,
          totalDose: 1
        };
      }
      return null;
    }
  }
}
</script> 